package cn.com.xyc.controller;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.xyc.common.MD5;
import cn.com.xyc.common.XuProUtils;
import cn.com.xyc.pojo.User;
import cn.com.xyc.service.SystemService;

import com.google.code.kaptcha.Constants;

@Controller
@RequestMapping("/system")
public class SystemController {
	@Autowired
	private SystemService systemService;
	@Autowired
	private JavaMailSender mailSender;

	/**
	 * 校验校验码
	 * 
	 * @param kaptchaInput
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/checkKaptcha")
	@ResponseBody
	public String checkKaptcha(String kaptchaInput, HttpServletRequest request)
			throws IOException {
		String currentCode = (String) request.getSession().getAttribute(
				Constants.KAPTCHA_SESSION_KEY);
		if (StringUtils.isEmpty(kaptchaInput)
				|| !currentCode.equals(kaptchaInput)) {
			return "false";
		} else {
			return "true";
		}
	}

	/**
	 * 校验用户名是否重复注册
	 * 
	 * @param username
	 * @return
	 */
	@RequestMapping("/checkUsername")
	@ResponseBody
	public String checkUsername(String username) {
		if (systemService.checkUsername(username)) {
			return "true";
		} else {
			return "false";
		}
	}

	/**
	 * 跳转到注册页面
	 * 
	 * @return
	 */
	@RequestMapping("/registerPage")
	public String registerPage(@ModelAttribute("user") User user) {
		return "system/user/register";
	}

	/**
	 * 保存用户 注册信息，并发送用户激活邮件
	 * 
	 * @param user
	 * @param model
	 * @return
	 */
	@RequestMapping("/saveRegisterInfo")
	public String saveRegisterInfo(User user, Model model) {
		String password = user.getPassword();
		String username = user.getUsername();
		Map<String, String> pwdInfo = MD5.encode(password, username);
		user.setPassword(pwdInfo.get("pwd"));
		user.setSalt(pwdInfo.get("salt"));
		user.setActivation(pwdInfo.get("code"));
		XuProUtils.sendMail(username, "xyc312319@163.com", mailSender,
				"http://localhost:8020/XuPro/system/checkUserActiveCode?activeCode="
						+ pwdInfo.get("code"));
		systemService.saveRegisterInfo(user);
		model.addAttribute("email", username);
		return "system/user/accountActivation";
	}

	@RequestMapping("/checkUserActiveCode")
	public String checkUserActiveCode(String activeCode) {
		boolean result = systemService.checkUserActiveCode(activeCode);
		if (result) {
			return "system/user/activeSuccess";
		} else {
			return null;
		}
	}

	@RequestMapping("/examplePage")
	public String examplePage(HttpServletRequest request) {
		 return "system/main/example";
	}

}
